package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MainActivity;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.ImageHelper;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.entity.NewsInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.ArrayList;

/**
 * Created by user on 2016/6/15.
 */
public class NewsActivity extends Activity implements View.OnClickListener {
    private Button tv_news_return;
    private Intent intent;
    private PullToRefreshListView mPullRefreshListView;
    private NetworkImageViewAdapter adapter;
    private ArrayList<NewsInfo> newsList;
    private String firstPageUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        tv_news_return=(Button)findViewById(R.id.tv_news_return);
        tv_news_return.setOnClickListener(this);
        //PullToRefreshListView
        initPullToRefreshListView();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_news_return:
                intent=new Intent(this, MainActivity.class);
                startActivity(intent);
                //从左往右切换
                this.overridePendingTransition(R.animator.slide_left_in,0);
                break;
            default:
                break;
        }
    }

    //PullToRefreshListView
    private void initPullToRefreshListView(){
        mPullRefreshListView=(PullToRefreshListView)findViewById(R.id.news_refresh_listlview);
        ILoadingLayout startLabels = mPullRefreshListView.getLoadingLayoutProxy(true,false);
        ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(false,true);
        startLabels.setPullLabel(getString(R.string.startPullLabel));
        startLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        startLabels.setReleaseLabel(getString(R.string.releaseLabel));
        endLabels.setPullLabel(getString(R.string.endPullLabel));
        endLabels.setRefreshingLabel(getString(R.string.refreshingLabel));
        endLabels.setReleaseLabel(getString(R.string.releaseLabel));
        //mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        newsList = new ArrayList<NewsInfo>();
        adapter = new NetworkImageViewAdapter(this,newsList);
        mPullRefreshListView.setAdapter(adapter);
        //默认读取第1页10条数据
        firstPageUrl = "http://"+ Constant.host+":"+Constant.port+"/api/NewsInfo/GetSpiltPageList/1/"+Constant.pageSize;
        LoadingDialog.showLoading(this,"请稍后...");
        LoadNewsData(firstPageUrl);
        //点击事件
        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //PullRefreshListView加了headerview（就是“下拉刷新”那个提示，位置id=0）,以及footerview,所以用position定位
                ListView lv = (ListView)parent;
                Object object=lv.getItemAtPosition(position);
                NewsInfo news = (NewsInfo)object;
                //传递news对象
                intent =new Intent(NewsActivity.this,NewsInfoActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("news", news);
                intent.putExtras(bundle);
                startActivity(intent);
                //从右往左切换
                NewsActivity.this.overridePendingTransition(R.animator.slide_right_in,0);
            }
        });
        //刷新
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //执行刷新函数
                //new RefreshDataTask().execute();
                adapter.remove();//清空之前的数据(这里偷懒了)
                LoadNewsData(firstPageUrl);
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                int count = adapter.getCount();
                int iszero=count%Constant.pageSize;
                int currentPageIndex=iszero==0?(count/Constant.pageSize):(count/Constant.pageSize+1);
                int nextPageIndex=currentPageIndex+1;
                String url = "http://"+ Constant.host+":"+Constant.port+"/api/NewsInfo/GetSpiltPageList/"+nextPageIndex+"/"+Constant.pageSize;
                LoadNewsData(url);
            }
        });
//        mPullRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
//            @Override
//            public void onLastItemVisible() {
//
//            }
//        });
    }

    private void LoadNewsData(String url){

        final StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        showData(result);
                        //下拉刷新或上拉加载后执行
                        mPullRefreshListView.onRefreshComplete();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(NewsActivity.this, "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                });
        request.setTag("getNewsData");
        MyApplication.getHttpQueue().add(request);
    }

    //设置PullToRefreshListView适配器
    private void showData(String json){
        try {
            //因为下面可能会关闭上拉加载功能，所以执行此方法前开启
            mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            Gson gson = new Gson();
            ArrayList<NewsInfo> tempList = gson.fromJson(json, new TypeToken<ArrayList<NewsInfo>>() {}.getType());
            if(tempList!=null&&tempList.size()>0) {
                adapter.addItem(tempList);
                adapter.notifyDataSetChanged();
            }
            else {
                if(adapter.getCount()>0) {
                    Toast.makeText(this, "没有更多数据了",
                            Toast.LENGTH_SHORT).show();
                    mPullRefreshListView.onRefreshComplete();
                    //没有更多数据了，关闭上拉加载功能
                    mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                }
                else {
                    Toast.makeText(this, "暂无数据",
                            Toast.LENGTH_SHORT).show();
                    //暂无数据，关闭上拉下拉功能
                    mPullRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                }
            }
        }
        catch (Exception e){
        }
    }
    private class NetworkImageViewAdapter extends BaseAdapter {
        private LayoutInflater layoutInflater = null;
        private ArrayList<NewsInfo> newsInfolist=null;
        class ViewHolder {
            TextView title;
            TextView posttime;
            TextView typename;
            NetworkImageView image;
        }
        public NetworkImageViewAdapter(Context context,ArrayList<NewsInfo> list)
        {
            layoutInflater = LayoutInflater.from(context);
            newsInfolist=list;
        }
        @Override
        public int getCount() {
            return newsInfolist == null ? 0 : newsInfolist.size();
        }

        @Override
        public Object getItem(int position) {
            return newsInfolist == null ? null : newsInfolist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addItem(ArrayList<NewsInfo> nlist){
            newsInfolist.addAll(nlist);
        }

        public void remove(){
            newsInfolist.clear();
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            String baseUrl="http://"+ Constant.host+":"+Constant.port;
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.newslist_item, null);
                viewHolder.title = (TextView) convertView.findViewById(R.id.tv_newslist_title);
                viewHolder.posttime = (TextView) convertView.findViewById(R.id.tv_newslist_time);
                viewHolder.typename=(TextView)convertView.findViewById(R.id.tv_newslist_type);
                viewHolder.image = (NetworkImageView) convertView.findViewById(R.id.niv_news_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            NewsInfo news = newsInfolist.get(position);
            viewHolder.title.setText(news.getNewsName());
            viewHolder.posttime.setText(news.getDisplayTime());
            viewHolder.typename.setText(news.getNewsTypeName());
            ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), viewHolder.image, baseUrl+news.getNewsImg());
            return convertView;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("getNewsData");
    }
}
